/*
 * @Description: 
 * @Author: lijiajin
 * @Date: 2020-07-06 10:42:47
 * @LastEditTime: 2020-07-10 12:05:54
 * @LastEditors: lijiajin
 */


//  ******************************************************** 公共 ***************************************************

$(function () {

    // 滚动条
    $('.nano').nanoScroller();

    // 按钮
    $(".turn-btn-div input[type='checkbox']").change(function () {
        if ($(this).prop("checked")) {
            $(this).closest(".icon").addClass("iconkaiguananniu-kai").removeClass("iconswitch-off");
        } else {
            $(this).closest(".icon").addClass("iconswitch-off").removeClass("iconkaiguananniu-kai");
        }
    })

    // 多选
    $(".check-box-div input[type='checkbox']").change(function () {
        if ($(this).prop("checked")) {
            $(this).closest(".icon").addClass("iconfuxuankuangxuanzhong").removeClass("iconduoxuanweixuanzhong");
        } else {
            $(this).closest(".icon").addClass("iconduoxuanweixuanzhong").removeClass("iconfuxuankuangxuanzhong");
        }
    })

    // 翻译弹窗-语言多选
    $(".wrap-translate-dialog").on("change", ".top input[type='checkbox']", function () {
        if ($(this).prop("checked")) {
            if ($(".wrap-translate-dialog .top input[type='checkbox']:checked").length > 5) {
                $(this).prop("checked", false);
                $(this).closest(".icon").addClass("iconduoxuanweixuanzhong").removeClass("iconfuxuankuangxuanzhong");
                $(".wrap-translate-dialog .top .iconduoxuanweixuanzhong").css("color", "#efefef");
            } else if ($(".wrap-translate-dialog .top input[type='checkbox']:checked").length == 5) {
                $(".wrap-translate-dialog .top .iconduoxuanweixuanzhong").css("color", "#efefef");
            } else {
                $(".wrap-translate-dialog .top .iconduoxuanweixuanzhong").css("color", "#bbb");
            }
        } else {
            $(".wrap-translate-dialog .top .iconduoxuanweixuanzhong").css("color", "#bbb");
        }
    })

    // seo优化 - seo设置--批量编辑多选
    $(".wrap-seo").on("change", "table tbody input[type='checkbox']", function () {
        if ($(this).prop("checked")) {
            $(".wrap-seo").find(".seo-set-edit-all-form").append(`<input type="hidden" name="ids[]" value="${$(this).val()}"/>`)
        } else {
            $(".wrap-seo").find(".seo-set-edit-all-form").find("input[type='hidden'][value='" + $(this).val() + "']").remove();
        }
    })

    // 单选
    $(".radio-box-div input[type='radio']").change(function () {
        $(this).closest(".icon").addClass("icondanxuanxuanzhong").removeClass("icondanxuanxuanzhong-copy");
        $(this).closest(".radio-box-div").siblings(".radio-box-div").find(".icon").addClass("icondanxuanxuanzhong-copy").removeClass("icondanxuanxuanzhong");
    })

    // 切换语言
    $(".language-exchange .language-btn").click(function () {
        if ($(this).hasClass("active")) {
            return;
        } else {
            $(this).addClass("active").siblings().removeClass("active");
            $(".item-box[data-translate='true']").hide();
            $(".item-box[data-translate='true'][data-id='" + $(this).attr("data-id") + "']").show();
        }
    })

    // item 添加
    $(".item-box.item-list").on("click", ".add", function () {
        if ($(this).closest(".item-box").find(".item").length > parseInt($(this).attr("data-maxNum"))) {
            showToast("每个类型联系方式最多添加" + $(this).attr("data-maxNum") + "个", 3);
            return;
        }
        if ($(this).closest(".item-box").attr("data-translate") === "true") {
            $(".item-box.item-list[data-tag='" + $(this).closest(".item-box").attr("data-tag") + "']").each(function (index, item) {
                var html_ = '<div class="item ' + $(item).find(".add").attr("data-field") + '" data-num="' + (parseInt($(item).find(".item:last-of-type").attr("data-num")) + 1) + '">\n' +
                    '                    <p class="input">\n' +
                    $(item).find(".add").prev("p.input").html() +
                    '                    </p>\n' +
                    '                    <a href="javascript:;" class="icon iconfont iconshanchuanniu1 delete"></a>\n' +
                    '                </div>';
                $(item).append(html_);
            })
        } else {
            var html_ = '<div class="item ' + $(this).find(".add").attr("data-field") + '">\n' +
                '                    <p class="input">\n' +
                $(this).prev("p.input").html() +
                '                    </p>\n' +
                '                    <a href="javascript:;" class="icon iconfont iconshanchuanniu1 delete"></a>\n' +
                '                </div>';
            $(this).closest(".item-box").append(html_);
        }
    })

    // item 减少
    $(".item-box.item-list").on("click", ".delete", function () {
        if ($(this).closest(".item-box").attr("data-translate") === "true") {
            var num = $(this).closest(".item").attr("data-num");
            $(".item-box.item-list[data-tag='" + $(this).closest(".item-box").attr("data-tag") + "']").each(function (index, item) {
                $(item).find(".item[data-num='" + num + "']").remove();
            })
        } else {
            $(this).closest(".item").remove();
        }
    })

    // banner图添加
    $(".add-banner-item-btn").on("click", function () {
        if ($(".item-cell-box.item-cell-box-banner").length >= 6) {
            showToast("最多可以添加6张Banner图", 3);
            return;
        }
        $(this).closest(".item-box").before(`${$(this).attr("data-el")}`)
    })

    // banner图添加-html
    getBannerItemHtml($(".add-banner-item-btn"));

    window.addEventListener('message', function (e) {
        console.log("common.js:window.addEventListener");
        if (e.data.msg.type == "pic_bank_get_parent") {
            appendPic(e.data.msg.datas);
        }
    }, false);

})

/**
 * 提示信息
 * @param msg
 * @param icon  1:成功    2：失败    3：其他
 * @param type  1：提示不跳转   2：提示跳转链接  3：提示刷新页面
 * @param url
 */
function showToast(msg, icon, type, url) {
    console.log("showToast")
    alert("aaaaa")
    if (!layer) return;
    if (!arguments[1]) icon = 3;
    if (!arguments[2]) type = 1;
    if (!arguments[3]) url = "";
    if (type == 1) { // 提示不跳转
        console.log("type == 1")
        layer.msg(msg, {
            time: 15000000,
            icon: icon,
            skin: "show-toast-0" + icon,
        });

    } else if (type == 2) { // 提示跳转链接
        console.log("type == 2")
        layer.msg(msg, {
            time: 1500,
            icon: icon,
            skin: "show-toast-0" + icon,
            end: function () {
                location.href = url;
            }
        });
    } else if (type == 3) { // 提示刷新页面
        console.log("type == 3")
        layer.msg(msg, {
            time: 1500,
            icon: icon,
            skin: "show-toast-0" + icon,
            end: function () {
                location.reload();
            }
        });
    } else {
        console.log("type == else")
        layer.msg(msg);
    }

}

/**
 * 错误信息
 * @param msg 提示信息
 * @param obj  插入节点
 * @param redObj  红框元素
 */
function showMsg(msg, obj, redObj) {
    // $(obj).next()
    $(obj).after("<label class='m-error'>" + msg + "</label>");
    if (redObj) {
        $(redObj).addClass("red-border");
    }
}

/**
 * 清除错误提示
 * @param obj  清除插入节点
 * @param redObj  清除红框元素
 */
function removeErrorMsg(obj, redObj) {
    obj.next().remove();
    if (redObj) {
        redObj.removeClass("red-border");
    } else {
        obj.removeClass("red-border");
    }

}

/**
 * 输入框计数
 * @param input 输入框
 * @param span 计数信息
 * @param num 总数
 */
function calculateLength(obj, span, num) {
    $(span).html($(obj).val().length + "/" + num);
}

// 获取banner图添加item
function getBannerItemHtml(obj) {
    var titleHtml = '';
    var mgtNum = "mgt15";
    if ($(obj).parents(".area-banner-box").length > 0) {
        titleHtml = '<p class="item-title">图片<span>' + $(obj).attr("data-chicun") + '</span></p>';
        mgtNum = "mgt5";
    }
    // TODO  name值
    $(obj).attr("data-el", `<div class="item-cell-box item-cell-box-banner ui-sortable-handle">
                    ${titleHtml}
                    <div class="fl">
                        <div class="item-box">
                            <div class="item ${mgtNum}">
                                <div class="bank-pic-list-box banner-box">
                                    <ul class="bank-pic-list" data-maxNum="1" data-necessary="true" data-minNum="1">
                                        <li class="pic-item add-pic-btn" onclick="showPicBankDialog(this)"></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="fl info">

                        <div class="item-box" data-translate="true" data-id="1">
                            <p class="item-title">图片标题</p>
                            <div class="item">
                                <p class="input">
                                    <input type="text" class="check-input" name="[]" maxlength="110" data-length="110" data-lengthtext="图片标题不能超过110字符">
                                </p>
                            </div>
                        </div>
                        <div class="item-box" data-translate="true" data-id="2" style="display: none;">
                            <p class="item-title">图片标题</p>
                            <div class="item">
                                <p class="input">
                                    <input type="text" class="check-input" name="[]" data-length="255" data-lengthtext="图片标题不能超过255字符">
                                </p>
                            </div>
                        </div>
                        <div class="item-box" data-translate="true" data-id="3" style="display: none;">
                            <p class="item-title">图片标题</p>
                            <div class="item">
                                <p class="input">
                                    <input type="text" class="check-input" name="[]" data-length="255" data-lengthtext="图片标题不能超过255字符">
                                </p>
                            </div>
                        </div>

                        <div class="item-box" data-translate="true" data-id="1">
                            <p class="item-title">alt属性</p>
                            <div class="item">
                                <p class="input">
                                    <input type="text" class="check-input" name="[]" maxlength="110" data-length="110" data-lengthtext="alt属性不能超过110字符">
                                </p>
                            </div>
                        </div>
                        <div class="item-box" data-translate="true" data-id="2" style="display: none;">
                            <p class="item-title">alt属性</p>
                            <div class="item">
                                <p class="input">
                                    <input type="text" class="check-input" name="[]" data-length="255" data-lengthtext="alt属性不能超过255字符">
                                </p>
                            </div>
                        </div>
                        <div class="item-box" data-translate="true" data-id="3" style="display: none;">
                            <p class="item-title">alt属性</p>
                            <div class="item">
                                <p class="input">
                                    <input type="text" class="check-input" name="[]" data-length="255" data-lengthtext="alt属性不能超过255字符">
                                </p>
                            </div>
                        </div>

                        <div class="item-box">
                            <p class="item-title">链接</p>
                            <div class="item">
                                <p class="input">
                                    <input type="text" class="check-input" name="[]" data-url="请输入符合要求的链接" maxlength="200" data-length="200" data-lengthtext="链接不能超过200字符">
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="i-btn">
                        <a href="javascript:;" class="icon iconfont icontuodong"></a>
                        <a href="javascript:;" class="icon iconfont iconshanchuanniu delete-banner-item-btn" onclick="deleteBannerItem(this)"></a>
                    </div>
                    <div class="clear"></div>
                </div>`);
}

// 删除banner图item
function deleteBannerItem(obj) {
    $(obj).closest(".item-cell-box-banner").remove();
}

//  ******************************************************** 图片银行 ***************************************************

$(function () {
    // 图片银行选中
    $(".wrap-bank-pic li .check-box-div input[type='checkbox']").change(function () {
        if ($(this).prop("checked")) {
            $(this).closest("li").addClass("selected");
        } else {
            $(this).closest("li").removeClass("selected");
        }
        console.log("aaaa:" + $("#img_bank_box").find("li.selected").length)
        console.log("bbb:" + surplusPicNum);
        if ($("#img_bank_box").find("li.selected").length > surplusPicNum) {
            console.log("asasasasas")
            showToast("最多只能添加" + limitPicMaxNum + "张图片");
            $(this).prop("checked", false).closest("li").removeClass("selected").find(".check-box-div .icon").addClass("iconduoxuanweixuanzhong").removeClass("iconfuxuankuangxuanzhong");
        }
    })

    // 图片银行编辑图片名称
    $(".wrap-bank-pic li .edit-btn").click(function () {
        $(this).hide().siblings(".edit-input").val($(this).siblings("span").html()).show().focus();
    })

    // 图片银行编辑图片名称  失去焦点提交
    $(".wrap-bank-pic li .edit-input").blur(function () {
        // TODO
        $(this).hide();
        var this_ = $(this);
        var id = $(this).closest("li").attr("data-id");
        $.ajax({
            type: "POST",
            url: picBankEditPostUrl,
            data: {id:id, name: $(this).val()},
            dataType: "json",
            success: function (data) {
                if (data.code == 200) {
                    this_.siblings("span").html(this_.val()).attr("alt", this_.val()).attr("title", this_.val());
                } else {
                    showToast(data.msg, 2);
                }
            },
            error: function () {
                showToast("请求失败", 2);
            }
        });
    })

    // 图片银行编辑图片名称  回车提交
    $(".wrap-bank-pic li .edit-input").bind('keydown', function (event) {
        // TODO
        if (event.keyCode == "13") {
            $(this).hide();
            var this_ = $(this);
            $.ajax({
                type: "POST",
                url: "",
                data: {value: $(this).val()},
                dataType: "json",
                success: function (data) {
                    if (data.status == 200) {
                        this_.siblings("span").html(this_.val()).attr("alt", this_.val()).attr("title", this_.val());
                    } else {

                    }
                },
                error: function () {
                    showToast("请求失败", 2);
                }
            });
        }
    });

    // 图片银行 全选
    $(".wrap-bank-pic-page .ajax-bank-select-all-btn").click(function () {
        if ($(this).attr("data-type") == "0") {
            $(this).attr("data-type", "1");
            $(this).closest(".wrap-bank-pic-page").find("ul#img_bank_box").find("li").addClass("selected").find(".check-box-div .icon").addClass("iconfuxuankuangxuanzhong").removeClass("iconduoxuanweixuanzhong").find("input.checkbox-input").prop("checked", true);
        } else {
            $(this).attr("data-type", "0");
            $(this).closest(".wrap-bank-pic-page").find("ul#img_bank_box").find("li.selected").removeClass("selected").find(".check-box-div .icon").removeClass("iconfuxuankuangxuanzhong").addClass("iconduoxuanweixuanzhong").find("input.checkbox-input").prop("checked", false);
        }
    })

    // 添加分组
    var add_group_btn_able = true;
    $(".wrap-bank-pic-page .add-group-btn").click(function () {
        if (!add_group_btn_able) {
            return;
        }
        // TODO
        $.ajax({
            type: "POST",
            url: "",
            data: ids,
            dataType: "json",
            success: function (data) {
                if (data.status == 200) {

                } else {

                }
            },
            error: function () {
                showToast("请求失败", 2);
            },
            beforeSend: function () {
                add_group_btn_able = false;
                showLoading();
            },
            complete: function () {
                add_group_btn_able = true;
                hideLoading();
            }
        });
    })
})

// 打开图片银行
var layerBank;
var limitPicMaxNum; // 最大限制数量
var surplusPicNum; // 剩余数量
var isIframe = false;

function showPicBankDialog(obj, type_module=0) {
    if ($(obj).attr("data-isIframe") == "true") {
        isIframe = true;
    }
    $(".bank-pic-list").removeClass("current");
    $(obj).closest(".bank-pic-list").addClass("current");
    limitPicMaxNum = parseInt($(obj).closest(".bank-pic-list").attr("data-maxNum"));
    surplusPicNum = parseInt(limitPicMaxNum - $(obj).closest(".bank-pic-list").find("li").not(".add-pic-btn").length);
    console.log("limitPicMaxNum:" + limitPicMaxNum + ",surplusPicNum:" + surplusPicNum);
    // TODO
    layerBank = layer.open({
        type: 2,
        title: '选择图片',
        shadeClose: true,
        shade: 0.5,
        skin: 'pic-bank-dialog',
        offset: '20px',
        area: ['92.0%', '90%'],
        content: picBankUrl+'?type_module='+type_module,
        btn: ['确认', '返回'],
        yes: function (index, layero) {
            layer.close(index);
            var body = layer.getChildFrame('body', index);
            var selectedLi = body.find("ul#img_bank_box").find("li.selected");
            console.log("selectedLi.length:" + selectedLi.length);
            var datas = [];
            $(selectedLi).each(function (index, item) {
                var data = {};
                data.name = $(item).find(".name span").html();
                data.path = $(item).find(".img img").attr("src");
                datas.push(data);
            })
            console.log("选择图片："+JSON.stringify(datas))
            if (isIframe) {
                var Iframe = $("iframe")[0];
                (Iframe.contentWindow || Iframe.contentDocument).postMessage({
                    msg: {type: "pic_bank_get_parent", datas: datas}
                }, "http://xb.member.com");
            } else {
                appendPic(datas);
            }
        },
    });
}

// 验证图片
function checkFile(el) {
    var files = el.files;
    var allowTypes;
    if ($(window.parent.document).find(".bank-pic-list.current").hasClass("bank-pic-list-icon")) {
        allowTypes = ["image/x-icon"];
    }else{
        allowTypes = ["image/jpeg", "image/png", "image/jpg"];
    }
    console.log("allowTypes:"+allowTypes);
    var maxFileSize = 2 * 1024 * 1024;
    var allowUpload = true;
    console.log("验证图片checkFile")
    if (files.length > surplusPicNum) {
        showToast("最多只能添加" + limitPicMaxNum + "张图片");
        allowUpload = false;
        return false;
    }

    for (var i = 0; i < files.length; i++) {
        var fileName = files[i].name;
        var fileType = files[i].type;
        var fileSize = files[i].size;
        console.log("fileType:"+files[i].type)

        if (fileSize > maxFileSize) {
            showToast("请上传小于2M的图片");
            allowUpload = false;
            return false;
        }

        var typeAccepted = false;
        for (var j = 0; j < allowTypes.length; j++) {
            if (allowTypes[j] == fileType) {
                typeAccepted = true;
                break;
            }
        }
        if (typeAccepted != true) {
            showToast("图片格式不支持");
            allowUpload = false;
            return false;
        }
    }

    if (allowUpload != true) {
        el.outerHTML = el.outerHTML; //清空选择的文件
        return false;
    }

    uploadPicBankFile($("#pic_bank_upload_form")[0], el);

}

// var fileExt = filePath.substring(filePath.lastIndexOf("."))
//     .toLowerCase();
function checkFileExt(ext) {
    if (!ext.match(/.jpg|.jpeg|.png|.icon/i)) {
        return false;
    }
    return true;
}

function checkFileIconExt(ext) {
    if (!ext.match(/.ico/i)) {
        console.log("checkFileIconExt")
        return false;
    }
    return true;
}

// 上传图片
function uploadPicBankFile(form, el) {
    console.log("uploadPicBankFile")
    var formData = new FormData(form);
    // TODO
    $.ajax({
        url: picBankUploadUrl,
        type: "POST",
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
        dataType: 'JSON',
        success: function (data) {
            if (data.code == 200) {
                if ($(".wrap-bank-pic-page").length > 0) {
                    appendPic(data.data);
                } else {
                    parent.appendPic(data.data);
                }
            } else {
                showToast(data.msg, 3);
            }
            el.outerHTML = el.outerHTML; //清空选择的文件
        },
        error: function () {
            showToast("请求失败", 2);
            el.outerHTML = el.outerHTML; //清空选择的文件
        }
    });
}

// 向页面插入新图片
function appendPic(datas) {
    if ($(".wrap-bank-pic").length > 0) {
        if ($(".wrap-bank-pic-page").length > 0) { // 图库
            console.log("appendPic-bank-page");
            var $ul = $("#img_bank_box");
            var html_ = "";
            for (var i = 0; i < datas.length; i++) {
                html_ = `<li data-id="">
                    <div class="img">
                        <img src="${datas[i].path}"/>
                        <div class="cover">
                            <div class="check-box-div">
                                <a href="javascript;:" class="icon iconfont iconduoxuanweixuanzhong">
                                    <input class="checkbox-input" type="checkbox" name="checkbox" value=""/>
                                </a>
                            </div>
                            <a href="javascript:;" class="magnifier icon iconfont iconfangdajing1" onclick="picBankDialogMagnifierPic(this);"></a>
                        </div>
                    </div>
                    <p class="name" title="">
                        <span>${datas[i].name}</span>
                        <a href="javascript:;" class="edit-btn icon iconfont iconbianjibi"></a>
                        <input type="text"name="editname" class="edit-input" value="${datas[i].name}"/>
                    </p>
                </li>`;
            }
            $ul.prepend(html_);
        }
    } else {
        console.log("appendPic-page");
        var $ul = $(".bank-pic-list.current");
        var maxNum = parseInt($ul.attr("data-maxNum"));
        var num = $ul.find("li").not(".add-pic-btn").length;
        var forLength = (maxNum - num) <= datas.length ? (maxNum - num) : datas.length;
        console.log("forLength:" + forLength);
        var html_ = "";
        if ($(".bank-pic-list.current").hasClass("bank-pic-list2")) { // 多张图片+删除+编辑名字
            for (var i = 0; i < forLength; i++) {
                html_ = `<li class="pic-item" data-id="">
                    <div class="img">
                        <img  src="${datas[i].path}"/>
                        <div class="cover">
                            <a href="javascript:;" class="icon iconfont iconshanchuanniu" onclick="deleteListPic(this)"></a>
                        </div>
                    </div>
                    <p class="name" title="">
                        <span>${datas[i].name}</span>
                        <a href="javascript:;" class="edit-btn icon iconfont iconbianjibi"></a>
                        <input type="text"name="editname" class="edit-input" value="${datas[i].name}"/>
                    </p>
                </li>`;
            }
        } else if ($(".bank-pic-list.current").closest(".bank-pic-list-box").hasClass("banner-box")) { // banner图
            for (var i = 0; i < forLength; i++) {
                html_ = `<li class="pic-item" data-id="">
                            <div class="img"><img src="${datas[i].path}" /></div>
                            <div class="delete">
                                <a href="javascript:;" class="icon iconfont iconbianji-bi" onclick="deleteListPicBanner(this)"></a>
                                <a href="javascript:;" class="magnifier icon iconfont iconfangdajing1" onclick="bannerPicMagnifier('${datas[i].path}');"></a>
                            </div>
                            <input class="pic-id" type="hidden" name="pic[]" value=""/>
                        </li>`;
            }
        } else { // 单张图片+删除
            console.log("单张图片+删除")
            if ($(".bank-pic-list.current").hasClass("bank-pic-list-icon")) {
                if (!checkFileIconExt(datas[0].path.substring(datas[0].path.lastIndexOf(".")).toLowerCase())) {
                    showToast("请上传ICON格式图片", 3);
                    return;
                }
            }
            for (var i = 0; i < forLength; i++) {
                html_ = `<li class="pic-item" data-id="">
                            <div class="img"><img src="${datas[i].path}" /></div>
                            <div class="delete"><a href="javascript:;" class="icon iconfont iconshanchuanniu" onclick="deleteListPic(this)"></a></div>
                            <input class="pic-id" type="hidden" name="thumb" value="${datas[i].path}"/>
                        </li>`;
            }
        }

        $ul.prepend(html_);
        console.log($ul.find("li").not(".add-pic-btn").length < parseInt($ul.attr("data-maxNum")))
        console.log($ul.find("li").not(".add-pic-btn").length)
        console.log(parseInt($ul.attr("data-maxNum")))
        if ($ul.find("li").not(".add-pic-btn").length < parseInt($ul.attr("data-maxNum"))) {
            $ul.find("li.add-pic-btn").show();
        } else {
            $ul.find("li.add-pic-btn").hide();
        }
        if (layerBank) {
            layer.close(layerBank);
        }

        if ($(".wrap-watermark").length > 0) { // 水印
            var src = $(".bank-pic-list .pic-item:nth-child(1)").find(".img img").attr("src");
            $(".wrap-watermark .preview img").attr("src", src);
        }
    }
}

// 删除列表图片
function deleteListPic(obj) {
    $(obj).closest(".bank-pic-list").find("li.add-pic-btn").show();
    $(obj).closest("li").remove();

    if ($(".wrap-watermark").length > 0) { // 水印
        $(".wrap-watermark .preview img").attr("src", "").css("width", "auto").css("height", "auto");
    }
}

// 删除列表图片-banner
function deleteListPicBanner(obj) {
    var addLi = $(obj).closest(".bank-pic-list").find("li.add-pic-btn");
    $(obj).closest("li").remove();
    $(addLi).show();
    showPicBankDialog($(addLi));
}

// 放大镜查看图片  图片银行页面/弹框
function picBankDialogMagnifierPic(obj) {
    var li = $(obj).closest("li");
    console.log($(li))
    var curr = 0;
    var src = [];
    $(obj).closest("ul").find("li").each(function (index, item) {
        console.log("index:" + index)
        console.log($(item))
        if ($(li).attr("data-id") == $(item).attr("data-id")) {
            console.log("index2:" + index)
            curr = index;
        }
        src.push($(item).find("img").attr("src"));
    })
    // TODO
    parent.window.parent.window.postMessage({
        msg: {type: "show_pic", curr: curr, src: src}
    }, "http://xb.member.com");
}

// 放大镜查看图片2  banner
function bannerPicMagnifier(url) {
    console.log("bannerPicMagnifier-url:" + url)
    // TODO
    parent.window.postMessage({
        msg: {type: "show_pic", curr: 0, src: [url]}
    }, "file:///F:/web-project/%E5%93%8D%E8%B4%9D/%E5%90%8E%E5%8F%B0/XBMemberWeb/admin.html");
}


//  ******************************************************** index ***************************************************
$(function () {
    if ($(".wrap-index").length > 0) {
        // TODO
        var indexLLData2 = ['2019-10-12', '2019-10-12', '2019-10-12', '2019-10-12', '2019-10-12', '2019-10-12', '2019-10-12']
        var indexLLData1 = [[110, 200, 212, 232, 122, 357, 345], [120, 132, 101, 134, 90, 230, 210]]
        showIndexCharts(indexLLData1, indexLLData2);

        var indexResourceData2 = ['直接访问', '站内跳转', '站内搜索', 'Google AD', 'Facebook']
        var indexResourceData1 = [
            {value: 335, name: '直接访问', proportion: "20%"},
            {value: 310, name: '站内跳转', proportion: "20%"},
            {value: 234, name: '站内搜索', proportion: "20%"},
            {value: 135, name: 'Google AD', proportion: "20%"},
            {value: 1548, name: 'Facebook', proportion: "20%"}
        ]
        showIndexChaertsResource(indexResourceData1, indexResourceData2);
    }
})

// show index echarts
function showIndexCharts(indexLLData1, indexLLData2) {
    var indexLLChart = echarts.init(document.getElementById("index_liuliang_chart"));
    var indexLLChartOption = {
        title: {
            show: false,
            text: '堆叠区域图'
        },
        tooltip: {
            trigger: 'axis',
            color: "black",
            backgroundColor: '#fff',
            extraCssText: 'box-shadow: 0 0 6px 3px rgba(0,0,0, 0.2);',
            axisPointer: {
                type: 'line',
                z: 1,
                lineStyle: {
                    type: 'dashed',
                    color: "#ddd"
                }
            },
            textStyle: {
                color: "black"
            },
        },
        legend: {
            show: false,
            data: ['浏览次数', '独立访客']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                axisLine: {
                    show: true,
                    lineStyle: {
                        type: 'dashed',
                        color: "#eef1f3"
                    },
                },
                axisLabel: {
                    formatter: '{value}',
                    textStyle: {
                        color: '#333'
                    }
                },
                data: indexLLData2
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisLine: {
                    show: false,
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        type: 'dashed',
                        color: "#eef1f3"
                    }
                },
                axisLabel: {
                    formatter: '{value}k'
                }
            }
        ],
        series: [
            {
                name: '浏览次数',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 2,
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgba(255,171,43,0.2)'
                        }, {
                            offset: 1,
                            color: 'rgba(255,171,43,0)'
                        }]),
                        opacity: 1
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#ffab2b', //改变折线点的颜色
                        lineStyle: {
                            color: '#ffab2b' //改变折线颜色
                        }
                    }
                },
                data: indexLLData1[0]
            },
            {
                name: '独立访客',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 2,
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgba(58,90,151,0.2)'
                        }, {
                            offset: 1,
                            color: 'rgba(58,90,151,0)'
                        }]),
                        opacity: 1
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#3a5a97', //改变折线点的颜色
                        lineStyle: {
                            color: '#3a5a97' //改变折线颜色
                        }
                    }
                },
                data: indexLLData1[1]
            }
        ]
    };
    indexLLChart.setOption(indexLLChartOption);
    window.onresize = function () {
        setTimeout(function () {
            indexLLChart.resize();
        }, 1000)
    }
}


function showIndexChaertsResource(indexResourceData1, indexResourceData2) {
    var indexReChart = echarts.init(document.getElementById("index_resource_chart"));
    var indexReChartOption = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
            orient: 'vertical',
            y: 'bottom',
            x: 'center',
            icon: "circle",
            itemWidth: 8,
            itemHeight: 8,
            itemGap: 10,
            textStyle: {
                color: '#999',
                fontSize: 12
            },
            formatter: function (name) {
                var target;
                var proportion;
                for (var j = 0; j < indexResourceData1.length; j++) {
                    if (indexResourceData1[j].name === name) {
                        target = indexResourceData1[j].value
                        proportion = indexResourceData1[j].proportion
                    }
                }
                var arr = [name + "     " + target + "     占比" + proportion];
                return arr

            },
            data: indexResourceData2
        },
        series: [
            {
                name: '访问来源',
                type: 'pie',
                radius: ['20%', '40%'],
                center: ['50%', '30%'],//设置饼图位置
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '10'
                    }
                },
                itemStyle: {
                    normal: {
                        borderWidth: 3,
                        borderColor: '#fff',
                    }
                },
                labelLine: {
                    show: false
                },
                data: indexResourceData1
            }
        ]
    };
    indexReChart.setOption(indexReChartOption);
    window.onresize = function () {
        indexReChart.resize();
    }
}


//  ******************************************************** 网站管理 ***************************************************
$(function () {

    // 基础设置-基础信息-是否关闭网站
    $(".item-box-close-website").find("input[type='checkbox']").change(function () {
        if ($(this).prop("checked")) {
            $(".item-box-fwzh").find("input[type='text']").attr("data-empty", "请输入访问账号");
            $(".item-box-fwmm").find("input[type='password']").attr("data-empty", "请输入访问密码");
        } else {
            $(".item-box-fwzh").find("input[type='text']").removeAttr("data-empty");
            $(".item-box-fwmm").find("input[type='password']").removeAttr("data-empty");
        }
    })

    // 语言设置
    $(".wrap-webmg-language .language-list .list li").find("input[type='checkbox']").on("change", function () {
        var maxNum = parseInt($("#max_language_num").attr("data-num"));
        if ($(this).prop("checked")) {
            if ($(this).closest("li").hasClass("main")) {
                $(this).prop("checked", false);
                return;
            }
            if ($(".wrap-webmg-language .language-list .list li").find("input[type='checkbox']:checked").length > maxNum) {
                $(this).prop("checked", false);
                showToast("最多可选" + maxNum + "种语言", 3);
                return;
            }
            $(this).closest("li").addClass("checked");
        } else {
            if ($(this).closest("li").hasClass("main")) {
                $(this).prop("checked", true);
                return;
            }
            $(this).closest("li").removeClass("checked");
        }
    })

    // 默认语言设置
    $(".wrap-webmg-language .item-box").find(".set-language-btn").find("input[type='radio']").on("click", function () {
        $(this).closest(".set-language-btn").removeClass("layui-btn-primary2").siblings(".set-language-btn").addClass("layui-btn-primary2").find("input[type='checkbox']").prop("checked", false);
        var currentId = $(this).val();
        $(".wrap-webmg-language .language-list .list li.main").removeClass("main").removeClass("checked").find("input[type='checkbox']").prop("checked", false);
        $(".wrap-webmg-language .language-list .list").find("input[type='checkbox'][value='" + currentId + "']").prop("checked", true).closest("li").addClass("checked").addClass("main");
    })

    // 导航设置-头部导航-栏目-自定义
    $(".wrap-webmg-navigation").on("change", ".select-lanmu", function () {
        // TODO 选中自定义导航
        if ($(this).val() == "1") {
            $(".item-box.item-box-xiala").hide().find("select").removeAttr("data-empty").prop("disabled", true);
            $(".item-box-url").show().find("input").attr("data-length", "200").attr("data-empty", "请输入URL").attr("data-url", "请输入正确的URL").prop("disabled", false);
        } else {
            $(".item-box-xiala").show().find("select").attr("data-empty", "请选择是否下拉").prop("disabled", false);
            $(".item-box-url").hide().find("input").removeAttr("data-length").removeAttr("data-empty").removeAttr("data-url").prop("disabled", true);
        }
    })

    // 首页内容-切换
    $(".wrap-webmg .shouye-left-content .click-area .area").on("click", function () {
        $(this).addClass("selected").siblings(".area").removeClass("selected");
        $(".area-item-box[data-tag='" + $(this).attr("data-tag") + "'][data-num='" + $(this).attr("data-num") + "'][data-type='" + $(this).attr("data-type") + "']").addClass("show").siblings(".area-item-box").removeClass("show");
    })

    // 选择模板
    $(".muban-list").on("click", ".item-muban-btn", function () {
        console.log($(this).closest("li").find("img").attr("src"));
        $(this).closest("li").addClass("selected").siblings("li").removeClass("selected");
        $("#show_muban_img").css("background", "url('" + $(this).closest("li").find("img").attr("src") + "') left top no-repeat");
        $(".use-muban-form").find("input.muban-id").val($(this).closest("li").attr("data-id"));
    })

})

// 添加导航
function checkNavigation(obj) {
    if ($('.navigation-list').find("li").length >= 10) {
        showToast("最多可以添加10个导航", 3);
        return false;
    }
    // TODO
    if ($(obj).attr("data-bottom") == "true") {
        window.location.href = 'file:///F:/web-project/%E5%93%8D%E8%B4%9D/%E5%90%8E%E5%8F%B0/XBMemberWeb/web-manage-navigation-bottom-add.html';
    } else {
        window.location.href = 'file:///F:/web-project/%E5%93%8D%E8%B4%9D/%E5%90%8E%E5%8F%B0/XBMemberWeb/web-manage-navigation-add.html';
    }

}

//  ******************************************************** setting ***************************************************
$(function () {
    // 水印位置
    $(".watermark-position-radio .radio-box-div input[type='radio']").change(function () {
        if ($(this).val() == 1) {
            $(".wrap-watermark .preview img").css("top", "0").css("left", "0").css("right", "unset").css("bottom", "unset").removeClass("center");
        } else if ($(this).val() == 2) {
            $(".wrap-watermark .preview img").css("top", "0").css("left", "unset").css("right", "0").css("bottom", "unset").removeClass("center");
        } else if ($(this).val() == 3) {
            $(".wrap-watermark .preview img").addClass("center");
        } else if ($(this).val() == 4) {
            $(".wrap-watermark .preview img").css("top", "unset").css("left", "0").css("right", "unset").css("bottom", "0").removeClass("center");
        } else if ($(this).val() == 5) {
            $(".wrap-watermark .preview img").css("top", "unset").css("left", "unset").css("right", "0").css("bottom", "0").removeClass("center");
        }
    })

    // 客服设置-选择客服类型
    $(".wrap-setting-kefu-dialog .select-kefu-type").on("change", function () {
        // TODO 选择WeChat
        if ($(this).val() == 3) {
            $(".item-box-erweima").show().find(".bank-pic-list").attr("data-empty", "请上传二维码图片").attr("data-necessary", "true");
        } else {
            $(".item-box-erweima").hide().find(".bank-pic-list").removeAttr("data-empty").removeAttr("data-necessary");
        }
        $('.nano').nanoScroller();
    })
})

// 水印图片加载监听
function watermarkPicLoaded(obj) {
    $(obj).css("width", $(obj).width() / 2)
}



